﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class Spring : MonoBehaviour 
{
	
	private  Vector3 startPos;
	private Vector3 endPos;//确定位置
	public float Y=1;
	public float Width=1;
	/// <summary>
	/// 比例系数
	/// </summary>
	public float k1=1;
	public float k2 = 1;

	private LineRenderer lineRenderer;

	public int pointNumber;//设置波动点个数
	public void FixedUpdate()
    {
	//		this.transform.ro = transform.parent.localRotation;
		startPos = transform.InverseTransformPoint(transform.parent.Find("Collider").Find("Fist").Find("Anchor1").position);
		startPos.z = 0;
		endPos =transform.InverseTransformPoint(transform.parent.Find("Collider").Find("Anchor2").position);
		Vector3 d = (endPos - startPos) / (pointNumber + 2);//两点之间均分等分
		float Distance = Vector3.Distance(endPos, startPos);
		lineRenderer.endWidth = Width-k2*Distance;
		lineRenderer.startWidth = Width-k2*Distance;

		for (int i = 1; i < pointNumber + 1; i++)
		{
			float h =( Y -k1*Distance)* (i % 2 == 0 ? 1 : -1);

			lineRenderer.SetPosition(i,transform.TransformPoint(startPos + d * i + new Vector3(0, h, 0)));
		}//循环随即设置波动点位置
		lineRenderer.SetPosition(0, transform.TransformPoint(startPos));
		lineRenderer.SetPosition(lineRenderer.positionCount - 1, transform.TransformPoint(endPos ));

	}
    private void OnEnable()
    {
        
		lineRenderer = GetComponent<LineRenderer>();

		lineRenderer.positionCount = pointNumber +2;//波动点加上起点和终点

	}
}
